package 滑动窗口;

public class 将x减为0的最小操作数 {
    public static int solustion(int[] nums, int x) {
        int sum1 = 0,sum = 0;
        int len = -1;
       /* for (int z = 0; z < nums.length; z++) {
            sum1 += nums[z];
        }*/
        for(int a:nums) sum1+=a;
        int target = sum1 - x;
        // 处理细节
        if(target < 0){
            return -1;
        }
        for(int left = 0,right = 0;right< nums.length ; right++){
            sum+=nums[right]; //进窗口
            while(sum > target){
                sum-=nums[left++];//出窗口
               // left++;
            }
            if(sum == target){
                len = Math.max(len,right-left+1); // 更新结果
            }
        }
        if(len == -1){
            return -1;
        }else{
            return nums.length-len;
        }
    }

    public static void main(String[] args) {
        int nums[] = {1,1,4,2,3};
        int x =5;

        int z =solustion(nums,x);
        System.out.println(z);
    }
}
